package kr.hkit.powerjava.chapter17;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ListPanel extends JPanel implements ActionListener, ListSelectionListener {
	private static final long serialVersionUID = 1L;
	
	private JTextField txtSelected;
	private JTextField textAddItem;
	private JButton btnAdd;
	private JList<String> list;

	public ListPanel() {
		initialize();
	}
	
	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel panelHeader = new JPanel();
		textAddItem = new JTextField();
		panelHeader.add(textAddItem);
		textAddItem.setColumns(10);
		
		btnAdd = new JButton("리스트 항목 추가");
		btnAdd.addActionListener(this);
		panelHeader.add(btnAdd);
		add(panelHeader, BorderLayout.NORTH);
		
		JPanel panelCenter = new JPanel();
		list = new JList<String>();
		list.addListSelectionListener(this);
		list.setModel(new DefaultListModel<String>());
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setViewportView(list);
		panelCenter.add(scrollPane);
		add(panelCenter, BorderLayout.CENTER);
		
		JPanel panelBottom = new JPanel();
		
		JLabel lblItem = new JLabel("선택된 항목 :");
		panelBottom.add(lblItem);
		
		txtSelected = new JTextField();
		txtSelected.setEditable(false);
		panelBottom.add(txtSelected);
		txtSelected.setColumns(10);
		
		add(panelBottom, BorderLayout.SOUTH);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		DefaultListModel<String> listmodel = (DefaultListModel<String>) list.getModel();
		listmodel.add(listmodel.getSize(), textAddItem.getText());
		list.updateUI();
		textAddItem.setText("");
		textAddItem.requestFocus();		
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		txtSelected.setText(list.getSelectedValue());		
	}

}
